// Author: wsfuyibing <682805@qq.com>
// Date: 2025-06-11

package services

import (
	"context"
	"gitee.com/go-libs/db-xorm/db"
	"server/app/errs"
	"server/app/http/models"
	"server/app/kind"
)

// Add
// 添加记录.
func (o *ArcadeFinanceService) Add(ctx context.Context, req *models.ArcadeFinance) (model *models.ArcadeFinance, err error) {
	var sess *db.Session

	// 1. 获取连接.
	if sess, err = o.Dao.Master(ctx); err != nil {
		err = errs.ErrDatabaseQuery
		return
	}

	// 2. 添加记录.
	if _, err = sess.Insert(req); err != nil {
		err = errs.ErrDatabaseQuery
	}
	return
}

// AddExpense
// 添加支出.
func (o *ArcadeFinanceService) AddExpense(ctx context.Context, arcade *models.Arcades, cost kind.Balance, fk kind.FinanceKind, msg, params string) (model *models.ArcadeFinance, err error) {
	return o.Add(ctx, &models.ArcadeFinance{
		ArcadeId: arcade.Id,
		Date:     db.NewDate(),
		Type:     kind.FinanceTypeExpense,
		Cost:     cost,
		Kind:     fk,
		Params:   params,
		Message:  msg,
	})
}

// AddIncome
// 添加收入.
func (o *ArcadeFinanceService) AddIncome(ctx context.Context, arcade *models.Arcades, cost kind.Balance, fk kind.FinanceKind, msg, params string) (model *models.ArcadeFinance, err error) {
	return o.Add(ctx, &models.ArcadeFinance{
		ArcadeId: arcade.Id,
		Date:     db.NewDate(),
		Type:     kind.FinanceTypeIncome,
		Cost:     cost,
		Kind:     fk,
		Params:   params,
		Message:  msg,
	})
}

// Paging
// 流水分页.
func (o *ArcadeFinanceService) Paging(ctx context.Context, data map[string]any, page, size int) (list []*models.ArcadeFinance, total int64, err error) {
	var sess *db.Session
	if sess, err = o.Dao.Slaver(ctx); err == nil {
		if total, err = sess.Where(data).Count(models.ArcadeFinance{}); err == nil && total > 0 {
			err = sess.Where(data).OrderBy("created_at DESC").Limit(size, (page-1)*size).Find(&list)
		}
	}
	return
}
